﻿using System;
using System.Collections.Generic;
using System.Linq;
using MartinRL.ProjectEuler.Sequences;

namespace MartinRL.ProjectEuler
{
    public class Problem026
    {
        // possible refactoring: use reptend prime algo: http://mathworld.wolfram.com/FullReptendPrime.html

        private readonly IList<int> decimals = new List<int>();
        private const int DIVIDEND = 1;
        private const int MAX_DIVISOR = 999;

        public int FindTheDivisorThatGivesTheLongestRecurringCycle()
        {
            return new IntPrimeSequence()
                .TakeWhile(d => d <= MAX_DIVISOR)
                .Select(d => new { Divisor = d, RecurringCycleLength = CalculateRecurringCycleLengthFor(d) })
                .OrderByDescending(drcl => drcl.RecurringCycleLength)
                .First()
                .Divisor;
        }

        internal int CalculateRecurringCycleLengthFor(int divisor)
        {
            decimals.Clear();

            int remainder;
            Math.DivRem(DIVIDEND * 10, divisor, out remainder);

            return CalculateRecurringCycleLengthFor(remainder, divisor);
        }

        private int CalculateRecurringCycleLengthFor(int dividend, int divisor)
        {
            if (dividend == DIVIDEND)
                return decimals.Count() + 1; 

            int remainder;
            var quotient = Math.DivRem(dividend * 10, divisor, out remainder);

            decimals.Add(quotient);
           
            if (remainder == 0)
                return 0;

            return CalculateRecurringCycleLengthFor(remainder, divisor);
        }
    }
}